import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:intl/intl.dart';
import 'package:sqflite/sqflite.dart';
import '../core/error_handler.dart';

/// 优化后的文件服务类
/// 减少重复的初始化检查，统一错误处理
class OptimizedFileServe {
  static final OptimizedFileServe _instance = OptimizedFileServe._internal();
  
  late String _appDataDir;
  bool _initialized = false;
  Database? _memoryDatabase;

  factory OptimizedFileServe() => _instance;
  OptimizedFileServe._internal();

  /// 获取应用数据目录
  String get appDataDir {
    _ensureInitialized();
    return _appDataDir;
  }

  /// 确保服务已初始化
  void _ensureInitialized() {
    if (!_initialized) {
      throw StateError('FileServe服务尚未初始化，请先调用initialize()方法');
    }
  }

  /// 初始化文件服务
  Future<void> initialize() async {
    if (_initialized) return;
    
    try {
      await _initializeDirectories();
      await _initializeMemoryDatabase();
      await _ensureUserGuideExists();
      
      _initialized = true;
      print('✅ FileServe初始化完成，目录: $_appDataDir');
    } catch (e) {
      throw AppError(
        type: AppErrorType.file,
        message: '文件服务初始化失败',
        details: e.toString(),
        originalError: e,
      );
    }
  }

  /// 初始化目录结构
  Future<void> _initializeDirectories() async {
    // 获取应用数据目录
    Directory appDir;
    if (Platform.isAndroid) {
      try {
        final externalDir = await getExternalStorageDirectory();
        if (externalDir != null) {
          _appDataDir = path.join(externalDir.parent.path, 'patchouli_knowledge');
        } else {
          appDir = await getApplicationDocumentsDirectory();
          _appDataDir = path.join(appDir.path, 'patchouli_knowledge');
        }
      } catch (e) {
        appDir = await getApplicationDocumentsDirectory();
        _appDataDir = path.join(appDir.path, 'patchouli_knowledge');
      }
    } else {
      appDir = await getApplicationDocumentsDirectory();
      _appDataDir = path.join(appDir.path, 'patchouli_knowledge');
    }

    // 创建基础目录
    final baseDir = Directory(_appDataDir);
    if (!await baseDir.exists()) {
      await baseDir.create(recursive: true);
    }

    // 创建子目录
    final subDirs = ['docs', 'doc', 'chat', 'config', 'temp', 'cache'];
    for (final dir in subDirs) {
      final directory = Directory(path.join(_appDataDir, dir));
      if (!await directory.exists()) {
        await directory.create(recursive: true);
      }
    }
  }

  /// 初始化内存数据库
  Future<void> _initializeMemoryDatabase() async {
    try {
      final dbPath = path.join(_appDataDir, 'memory.db');
      _memoryDatabase = await openDatabase(
        dbPath,
        version: 1,
        onCreate: _createMemoryTables,
      );
    } catch (e) {
      print('内存数据库初始化失败: $e');
    }
  }

  /// 创建内存数据库表
  Future<void> _createMemoryTables(Database db, int version) async {
    await db.execute('''
      CREATE TABLE IF NOT EXISTS conversations (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        content TEXT NOT NULL,
        timestamp INTEGER NOT NULL
      )
    ''');
    
    await db.execute('''
      CREATE TABLE IF NOT EXISTS documents (
        id TEXT PRIMARY KEY,
        title TEXT NOT NULL,
        content TEXT,
        tags TEXT,
        created_at INTEGER NOT NULL,
        updated_at INTEGER NOT NULL
      )
    ''');
  }

  /// 确保用户指南文件存在
  Future<void> _ensureUserGuideExists() async {
    final docDir = Directory(path.join(_appDataDir, 'doc'));
    final aboutFile = File(path.join(docDir.path, '知拾食用指南.md'));
    
    if (!await aboutFile.exists()) {
      const defaultContent = '''
# 知拾使用指南

## 欢迎使用知拾！

这是您的个人知识库管理系统。

### 主要功能
- 📚 文档上传和管理
- 🤖 AI智能问答
- 📱 智能截图识别
- 🏷️ 自动标签分类
''';
      await aboutFile.writeAsString(defaultContent);
    }
  }

  /// 安全执行操作的包装器
  Future<T> _safeExecute<T>(Future<T> Function() operation) async {
    _ensureInitialized();
    try {
      return await operation();
    } catch (e) {
      throw ErrorHandler.handleError(e);
    }
  }

  /// 读取用户信息
  Future<Map<String, dynamic>?> readUserInfo() async {
    return _safeExecute(() async {
      final file = File(path.join(_appDataDir, 'config', 'user_info.json'));
      if (!await file.exists()) return null;
      
      final content = await file.readAsString();
      return jsonDecode(content) as Map<String, dynamic>;
    });
  }

  /// 保存用户信息
  Future<void> saveUserInfo(Map<String, dynamic> userInfo) async {
    return _safeExecute(() async {
      final file = File(path.join(_appDataDir, 'config', 'user_info.json'));
      await file.writeAsString(jsonEncode(userInfo));
    });
  }

  /// 获取配置
  Future<Map<String, dynamic>> getConfig(String configName) async {
    return _safeExecute(() async {
      final file = File(path.join(_appDataDir, 'config', '$configName.json'));
      
      if (!await file.exists()) {
        // 创建默认配置
        final defaultConfig = _getDefaultConfig(configName);
        await file.writeAsString(jsonEncode(defaultConfig));
        return defaultConfig;
      }
      
      final content = await file.readAsString();
      return jsonDecode(content) as Map<String, dynamic>;
    });
  }

  /// 保存配置
  Future<void> saveConfig(String configName, Map<String, dynamic> config) async {
    return _safeExecute(() async {
      final file = File(path.join(_appDataDir, 'config', '$configName.json'));
      await file.writeAsString(jsonEncode(config));
    });
  }

  /// 保存聊天记录
  Future<void> saveChatHistory(String filename, List<Map<String, dynamic>> messages) async {
    return _safeExecute(() async {
      final file = File(path.join(_appDataDir, 'chat', '$filename.json'));
      await file.writeAsString(jsonEncode(messages));
    });
  }

  /// 读取聊天记录
  Future<List<Map<String, dynamic>>> readChatHistory(String filename) async {
    return _safeExecute(() async {
      final file = File(path.join(_appDataDir, 'chat', '$filename.json'));
      if (!await file.exists()) return [];
      
      final content = await file.readAsString();
      final List<dynamic> jsonList = jsonDecode(content);
      return jsonList.map((e) => e as Map<String, dynamic>).toList();
    });
  }

  /// 保存文档
  Future<String> saveDocument({
    required String title,
    required String content,
    required String type,
    List<String>? tags,
    Map<String, dynamic>? metadata,
  }) async {
    return _safeExecute(() async {
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final docId = 'doc_$timestamp';
      
      final docData = {
        'id': docId,
        'title': title,
        'content': content,
        'type': type,
        'tags': tags ?? [],
        'metadata': metadata ?? {},
        'created_at': timestamp,
        'updated_at': timestamp,
      };
      
      final file = File(path.join(_appDataDir, 'docs', '$docId.json'));
      await file.writeAsString(jsonEncode(docData));
      
      return docId;
    });
  }

  /// 清理临时文件
  Future<void> cleanupTempFiles() async {
    return _safeExecute(() async {
      final tempDir = Directory(path.join(_appDataDir, 'temp'));
      if (await tempDir.exists()) {
        final List<FileSystemEntity> files = tempDir.listSync();
        for (final file in files) {
          try {
            if (file is File) {
              final stat = await file.stat();
              final age = DateTime.now().difference(stat.modified);
              // 删除超过1小时的临时文件
              if (age.inHours > 1) {
                await file.delete();
              }
            }
          } catch (e) {
            print('删除临时文件失败: ${file.path} - $e');
          }
        }
      }
    });
  }

  /// 获取默认配置
  Map<String, dynamic> _getDefaultConfig(String configName) {
    switch (configName) {
      case 'LLM':
        return {
          'model': 'qwen-plus',
          'api_key': 'sk-aa328698ca6f4a7c9c0dde0b9851a772',
          'base_url': 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
          'temperature': 0.7,
          'max_tokens': 2000,
        };
      case 'Dify':
        return {
          'api_key': '',
          'base_url': '',
          'dataset_id': '',
        };
      case 'OCR':
        return {
          'enable_llm_optimization': true,
          'confidence_threshold': 0.8,
        };
      default:
        return {};
    }
  }
} 